package com.nc.delivery_project.client.statistics;


import java.util.ArrayList;
import java.util.List;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.visualizations.IntensityMap;
import com.google.gwt.visualization.client.visualizations.corechart.AreaChart;
import com.google.gwt.visualization.client.visualizations.corechart.BarChart;
import com.google.gwt.visualization.client.visualizations.corechart.Options;
import com.google.gwt.visualization.client.visualizations.corechart.PieChart;
import com.google.gwt.visualization.client.visualizations.corechart.PieChart.PieOptions;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
import com.nc.delivery_project.client.ClientFactory;
import com.nc.delivery_project.client.request.DepartmentRequest;
import com.nc.delivery_project.shared.proxy.CountryProxy;
import com.nc.delivery_project.shared.proxy.DepartmentProxy;
import com.nc.delivery_project.shared.proxy.OrderWaypointProxy;


public class StatisticsActivity extends AbstractActivity implements StatisticsPresenter {

	 private StatisticsView view;
	
	 private ClientFactory clientFactory;
	 
	 private DepartmentRequest updateRequest;
	
	 private List<DepartmentProxy> deptsPr;
	
	 private List<CountryProxy> countries;
	 
	// private List<OrderWaypointProxy> ordersW;
	 
	 private int fetchedCount;
	
	//----------- временные данные ----------
	//----------------------------------------- 
	
	private List<DepartmentSample> depts;
	
	List<String> dates;
	
	String [] deptsStr = {"Dept1","Dept2","Dept3","Dept4","Dept5"};
	Integer [] v1 = {11,15,8,2,7,3,8};
	Integer [] v2 = {5,8,5,10,5,4,7};
	
	//--------------------------------
	
	public StatisticsActivity(StatisticsPlace place, ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
     	fetchDepts();
    	fetchDepartments();
    	fetchCountries() ;	
   // 	fetchOrderWaypoints();
    		
		if (view==null) {
			view = new StatisticsView();
		}
		
		view.setPresenter(this);
        panel.setWidget(view);
        view.start();

	}
	
	

	private void createVisualization() {
  
		view.panel.add(new Label("Visualization Statistics with GWT. "));
		view.panel.getElement().getStyle().setPropertyPx("margin", 15);
	    
		view.panel.add(view.tabPanel);	

    		          
		VisualizationUtils.loadVisualizationApi(new Runnable() {
			public void run() { 
				//можно добавить несколько вкладок
				view.tabPanel.add(createBarChartCountry(), "Countries(BarChart)");
				view.tabPanel.add(createIntensityMap(), "Map");
				view.tabPanel.add(createBarChart(), "Statistics(BarChart)");
	    	    view.tabPanel.add(createPieChart(), "Statistics(PieChart)");
				//view.tabPanel.add(createAreaChart(), "newStatistics");
				view.tabPanel.selectTab(0);	
			}
		}, BarChart.PACKAGE,PieChart.PACKAGE, AreaChart.PACKAGE, BarChart.PACKAGE,IntensityMap.PACKAGE);

	}
	  
	  

	public void fetchDepartments() {
	        final DepartmentRequest deptRequest = clientFactory.getRequestFactory().createDepartmentRequest();

	        deptRequest.read().with("city","city.statePr","city.statePr.country").fire(new Receiver<List<DepartmentProxy>>() {
	            @Override
	            public void onSuccess(List<DepartmentProxy> response) {
	            	GWT.log("departmentr fetched");
	            	deptsPr=response;
	            	if (++fetchedCount == 2) createVisualization();
	    //        	if (++fetchedCount == 3) createVisualization();
	            }

	            @Override
	            public void onFailure(ServerFailure error) {
	                super.onFailure(error);
	                GWT.log(error.toString());
	            }
	        });
	    }
	
	
	  	private void  fetchCountries() {
		
		clientFactory.getRequestFactory().createCountryRequest().read().fire(new Receiver<List<CountryProxy>>() {
	           
				@Override
	            public void onSuccess(List<CountryProxy> response) {
	                GWT.log("countries fetched");
	                countries=response;
	                if (++fetchedCount == 2) createVisualization();
	     //        	if (++fetchedCount == 3) createVisualization();
	            }
			    @Override
	            public void onFailure(ServerFailure error) {
	                super.onFailure(error);
	                GWT.log(error.toString());
	            }
	        });

		}

	/*	private void fetchOrderWaypoints() {
			clientFactory.getRequestFactory().createOrderWaypointRequest().read().with("department").fire(new Receiver<List<OrderWaypointProxy>>(){
				 @Override
		            public void onSuccess(List<OrderWaypointProxy> response) {
		            	GWT.log("orderWaypoints fetched");
		            	ordersW=response;
		            	if (++fetchedCount == 3) createVisualization();
		            }

		            @Override
		            public void onFailure(ServerFailure error) {
		                super.onFailure(error);
		                GWT.log(error.toString());
		            }
		        });
			});
			
		}
	*/

		private Widget createBarChartCountry() {
			
			   /* create a datatable */
			DataTable  data  = DataTable.create();
		    data.addColumn(ColumnType.STRING, "Country");
		    data.addColumn(ColumnType.NUMBER, "Departments");

		    for (int i = 0,k = 0; k < countries.size() ; i++,k++) {
				int numDept=0;
				for (int j = 0; j < deptsPr.size(); j++) {
					if (deptsPr.get(j).getCity().getStatePr().getCountry().getCountryId()==countries.get(k).getCountryId()) {
						numDept++;
				    }
				}
				if (numDept!=0) {
					data.addRows(1);
					data.setValue(i, 0, countries.get(k).getCountryTitle());
					data.setValue(i, 1, numDept);
				} else	{i--;}
			}
			      /* create bar chart */
		    Options options = BarChart.createOptions();
		    options.setWidth(600);
		    options.setHeight(400);
		    options.setReverseCategories(false);//true - отображение снизу вверх
		    options.setTitle("Statistics by Countries (total count of Departments = "+deptsPr.size()+")");
		    
			return new BarChart(data, options);
		}
		
		
			
		private Widget createIntensityMap() {
				com.google.gwt.visualization.client.visualizations.IntensityMap.Options options = 
					 com.google.gwt.visualization.client.visualizations.IntensityMap.Options.create();
			    options.setWidth(600);
			    options.setHeight(400);
			    options.setShowOneTab(true);
			   			
			    DataTable data = DataTable.create();
			    data.addColumn(ColumnType.STRING, "", "Country");
			    data.addColumn(ColumnType.NUMBER, "Departments by Counties", "a");
			 
			    for (int i = 0,k = 0; k < countries.size() ; i++,k++) {
					int numDept=0;
					for (int j = 0; j < deptsPr.size(); j++) {
						if (deptsPr.get(j).getCity().getStatePr().getCountry().getCountryId()==countries.get(k).getCountryId()) {
							numDept++;
					    }
					}
					if (numDept!=0) {
						
						data.addRows(1);
						data.setValue(i, 0, findCodByCountry(countries.get(k).getCountryTitle()));
						data.setValue(i, 1, numDept);
						data.setFormattedValue(i, 0, countries.get(k).getCountryTitle());
					} else	{i--;}
				}

			    return new IntensityMap(data, options);
		}
		
		private String findCodByCountry(String countryName){
			String countryId="";
			String [][] codC = {{"US", "United States"},
								{"CA", "Canada"},
								{"AU", "Australia"},
								{"BR", "Brazil"},
								{"DE", "Germany"},
								{"IN", "India"},
								{"JP", "Japan"},
								{"MX", "Mexico"},
								{"NL", "Netherlands"},
								{"CH", "Switzerland"},
								{"UA", "Ukraine"},
								{"GB", "United Kingdom"}};
			for (int i = 0; i < codC.length; i++) {
				if ( countryName.equalsIgnoreCase(codC[i][1])) {
					countryId = codC[i][0];
				}
			}
			
			return countryId;
		}
		

		private Widget createBarChart() {
			/* create a datatable */
		    DataTable data = DataTable.create();
		    data.addColumn(ColumnType.STRING, "Task");
		    data.addColumn(ColumnType.NUMBER, "Accepted orders");
		    data.addColumn(ColumnType.NUMBER, "Granted orders");
		    data.addRows(depts.size());

		    for (int i = 0; i < depts.size(); i++) {
				data.setValue(i, 0, depts.get(i).nameDept);//deptId()?? city+address
				data.setValue(i, 1, depts.get(i).acceptedOrders);//число принятых заказов
				data.setValue(i, 2, depts.get(i).grantedOrders);//число выданных заказов
			}
		    
		    /* create bar chart */
		    Options options = BarChart.createOptions();
		    options.setWidth(600);
		    options.setHeight(400);
		    options.setReverseCategories(false);//true - отображение снизу вверх
		    options.setIsStacked(true);//true - отображение в 1 столбец  Volume1 + Volume2 и их соотношение
		    options.setTitle("Statistics by volume of orders");
		 
		    return new BarChart(data, options);
		 
		  }
		  private Widget createPieChart() {
			    /* create a datatable */
			    DataTable data = DataTable.create();
			    data.addColumn(ColumnType.STRING, "Task");
			    data.addColumn(ColumnType.NUMBER, "Accepted orders");
			    data.addRows(depts.size());

			    for (int i = 0; i < depts.size(); i++) {
					data.setValue(i, 0, depts.get(i).nameDept);//deptId()??
					data.setValue(i, 1, depts.get(i).acceptedOrders);//число принятых заказов 
					// можно сделать - активность по принятым + выданным заказам
				//	data.setValue(i, 1, depts.get(i).volumeOfOrders1+depts.get(i).volumeOfOrders2);
				}

			    /* create pie chart */
			    PieOptions options = PieChart.createPieOptions();
			    options.setWidth(600);
			    options.setHeight(400);
			    options.set3D(true);
			    options.setTitle("Departments Activities");
			    return new PieChart(data, options);
			  }
		
		  void fetchDepts(){
			  // использование метода считывание из базы числа принятых и выданных заказов
			  // через сервис Orders? OrderWaypoint?
		 
			    depts = new ArrayList<DepartmentSample>();
			    for (int i = 0; i < deptsStr.length; i++) {
			    	depts.add( new DepartmentSample(deptsStr[i], v1[i], v2[i]));
				}
		  }
		  
	

	@Override
	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);
		
	}

	@Override
	public ClientFactory getClientFactory() {
		return clientFactory;
	}

}

class DepartmentSample{
	//Accepted Granted
	String nameDept;
	Integer acceptedOrders;
	Integer grantedOrders;
	
	public DepartmentSample(String nameDept, Integer acceptedOrders,
			Integer issuedOrders) {
		this.nameDept = nameDept;
		this.acceptedOrders = acceptedOrders;
		this.grantedOrders = issuedOrders;
	}
	
	   
}
